var express = require('express');
var router = express.Router();
const formidable = require('formidable')
const path = require('path')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* 文件上传表单页面 */
router.get('/portrait', (req, res, next) => {
  res.render('portrait')
})

/* 处理文件上传 */
router.post('/portrait', (req, res, next) => {
  const form = new formidable.IncomingForm({
    multiples: true,
    uploadDir: path.resolve(__dirname, '../public/images'),
    keepExtensions: true,
  })
  form.parse(req, (err, fields, files) => {
    if(err) {
      next(err)
      return
    }
    const url = `http://127.0.0.1:3000/images/${files.file[0].newFilename}`
    res.send(`<a href="${url}" target="_blank">${files.file[0].originalFilename}</a>`)
  })
})

module.exports = router;
